package com.ssm.util.alg.luckydraw;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 概率抽奖测试
 * 取一段长度按奖品数量、概率、概率取整常数确定长度
 * 然后随机去一个长度下标对应的奖品
 * 并且减去刚刚取完的商品
 */
public class TestA {

    public static Award lottery(List<Award> awards){
        //总的概率区间
        float totalPro = 0f;
        //存储每个奖品新的概率区间
        List<Float> proSection = new ArrayList<Float>();
        proSection.add(0f);
        //遍历每个奖品，设置概率区间，总的概率区间为每个概率区间的总和
        for (Award award : awards) {
            //每个概率区间为奖品概率乘以1000（把三位小数转换为整）再乘以剩余奖品数量
            totalPro += award.probability * 1000 * award.count;
            proSection.add(totalPro);
        }
        //获取总的概率区间中的随机数
        Random random = new Random();
        float randomPro = (float)random.nextInt((int)totalPro);
        //判断取到的随机数在哪个奖品的概率区间中
        for (int i = 0,size = proSection.size(); i < size; i++) {
            if(randomPro >= proSection.get(i) && randomPro < proSection.get(i + 1)){
                //抽完一个商品，对应数量减一
                if (i!=size-1){
                    Award award = (Award)awards.get(i);
                    award.setCount(award.getCount()-1);
                }
                return awards.get(i);
            }
        }
        return null;
    }

    public static void main(String[] args) {
        int size=10;
        List<Award> awards = new ArrayList<>();
        awards.add(new Award("a1",0.1f,1));
        awards.add(new Award("a2",0.2f,4));
        awards.add(new Award("a3",0.3f,2));
        awards.add(new Award("a4",0.05f,2));
        awards.add(new Award("a5",0.2f,1));
        try {

            for (int i = 0; i < 11; i++) {
                if (i==10){
                    System.out.println("奖品已抽完，请留意其他活动");
                    return;
                }
                System.out.println("恭喜您，抽到了：" + lottery(awards).getId());
                size--;
            }
        } catch (Exception e) {
            System.out.println("系统异常");
            e.printStackTrace();
        }
    }
}
